package fina2.dcs.system;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;

@Stateful
@LocalBinding(jndiBinding = "SysStringSession/local")
@Scope(ScopeType.SESSION)
@SuppressWarnings( { "unchecked" })
@AutoCreate
public class SysStringSession implements SysStringLocal,Serializable {

	@PersistenceContext
	private EntityManager em;
	
	@Logger
	private Log log;

	public List<SysString> getAllValues(String ids, BigDecimal langId) {
		List<SysString> list = em.createQuery("FROM " + SysString.class.getName() + " s WHERE LANGID=? AND RTRIM(ID) IN(" + ids + ") ORDER BY VALUE ASC").setParameter(1, langId).getResultList();
		return list;
	}

	public List<SysString> getAllValues(String ids) {
		return (List<SysString>) em.createQuery("FROM " + SysString.class.getName() + " s WHERE RTRIM(ID) IN(" + ids + ") ORDER BY VALUE ASC").getResultList();
	}

	@Remove
	@Destroy
	public void remove() {

	}

	public BigDecimal getMaxId() {
		BigDecimal maxId = new BigDecimal("0");
		try {
			maxId = (BigDecimal) em.createQuery("SELECT MAX(s.pk.id) FROM " + SysString.class.getName() + " s").getSingleResult();
			if (maxId == null)
				maxId = new BigDecimal("1");
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return maxId;
	}

	public void addString(SysString ss) {
		try {
			em.persist(ss);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}

	}

	public void removeString(SysStringPk pk) {
		try {
			SysString ss = em.find(SysString.class, pk);
			if (ss != null)
				em.remove(ss);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}

	}

	public void updateString(SysString ss) {
		try {
			em.merge(ss);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public List<SysString> findByValue(String value) {
		List<SysString> vals = null;
		try {
			if (value != null) {
				vals = em.createQuery("FROM " + SysString.class.getName() + " s WHERE RTRIM(s.value)=?").setParameter(1, value.trim()).getResultList();
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return vals;
	}

	public SysString findByPk(SysStringPk pk) {
		SysString ss = null;
		try {
			ss = em.find(SysString.class, pk);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return ss;
	}
}
